<style lang="scss"></style>

<script>

export default {
  props: {
    icon: {
      type: String,
      required: false,
      default: 'el-icon-question'
    },
    iconColor: {
      type: String,
      required: false,
      default: '#f90'
    },
    title: {
      type: String,
      required: false,
      default: '确定删除吗？'
    },
    cancelBtnText: {
      type: String,
      required: false,
      default: '取消'
    },
    confirmBtnText: {
      type: String,
      required: false,
      default: '确定'
    },
    confirmFn: {
      type: Function,
      required: true,
      default() {
        return () => {}
      }
    },
    cancelFn: {
      type: Function,
      required: false,
      default: null
    },
    isTextBtn:{
      type:Boolean,
      default:false
    }
  },
  data() {
    return {
      isPending: false,
      popconfirmVisible: false
    }
  },
  computed: {
    classes() {
      return this.buildClasses()
    },
    styles() {
      return this.buildStyles()
    }
  },
  methods: {
    buildClasses() {
      return {
        'el-popconfirm__icon': true,
        [this.icon]: true
      }
    },
    buildStyles() {
      return {
        color: this.iconColor
      }
    },
    closePopconfirm() {
      if (this.isPending) return

      if (typeof this.cancelFn === 'function') {
        this.cancelFn(() => {
          this.popconfirmVisible = false
        })
        return
      }

      this.popconfirmVisible = false
    },
    async confirm() {
      try {
        this.isPending = true
        const result = await this.confirmFn()
        this.isPending = false
        this.popconfirmVisible = false
        this.$emit('success', result)
      } catch (e) {
        this.isPending = false
        this.$emit('fail', e)
      }
    }
  }
}
</script>

<template>
  <el-popover v-model="popconfirmVisible" placement="top" trigger="click">
    <div class="el-popconfirm">
      <p class="el-popconfirm__main">
        <i :class="classes" :style="styles" />
        {{ title }}
      </p>
      <div class="el-popconfirm__action">
        <el-button size="mini" :disabled="isPending" type="text" @click="closePopconfirm">
          {{ cancelBtnText }}
        </el-button>
        <el-button size="mini" :disabled="isPending" :loading="isPending" type="primary" @click="confirm">
          {{ confirmBtnText }}
        </el-button>
      </div>
    </div>

    <!-- <span style="margin-left: 10px;"> -->
      <el-button v-if="isTextBtn" slot="reference" type="danger" size="small">删除</el-button>
    <el-button v-else slot="reference" circle plain type="danger" icon="el-icon-delete" />
    <!-- </span> -->
  </el-popover>
</template>
